// 清除用不到的图片
var fs = require("fs");
var join = require("path").join;

const imgsList = []
const contentList = []

function getJsonFiles(jsonPath) {
  function findJsonFile(path) {
    let files = fs.readdirSync(path);
    files.forEach(function(item, index) {
      let fPath = join(path, item);
      let stat = fs.statSync(fPath);
      if(stat.isDirectory() === true) {
        findJsonFile(fPath);
      }
      if(stat.isFile() === true && (/\.md$/).test(fPath)) {
        const data = fs.readFileSync(fPath, "utf-8");
        console.log(fPath);
        contentList.push(data)
      }
      if(stat.isFile() === true && (/\.(png|jpg|jpeg)$/).test(fPath)) {
        const res = fPath.match(/md\\assets\\(media\\)?(\S*)$/);
        res && imgsList.push({
          name: res[2],
          url: fPath
        });
      }
    });
  }
  findJsonFile(jsonPath);
  // console.log(imgsList);
  // console.log(contentList);
}
getJsonFiles("./md");

const Fuse = require('fuse.js')
const options = {
  includeScore: true,
  includeMatches: true,
  ignoreFieldNorm: true,
  ignoreLocation: true,
  findAllMatches: true,
  threshold: 0.1
}
const fuse = new Fuse(contentList, options)
// const result = fuse.search('image-20200826110754199')
// console.log(result[0]?.score);
// console.log(result[0] && Object.keys(result[0]));

imgsList.forEach(element => {
  const result = fuse.search(element.name)
  // console.log(result[0] && Object.keys(result[0]));
  if(!result[0]) {
    fs.unlinkSync(element.url)
  }
});
